var http_raw=require("http");
var express=require("express");
var app=express();
var http= require("http").Server(app);
var io=require('socket.io')(http);
var handlebars=require("express3-handlebars").create({ 
														defaultLayout: null	});
var aliveClient={};
var aliveList={}
var aliveCount=0;
ok=true;

function down(url, callback) {
  http_raw.get(url, function(res) {
    var data = "";
    res.on('data', function (chunk) {
      data += chunk;
    });
	res.on("end", function() {
	callback(data);
    });
  }).on("error", function() {
	callback(null);
  });
}

function addClient(socket){
	var cid=""
	function newId(){
		var Num=""; 
		for(var i=0;i<6;i++) 
		{ 
			Num+=Math.floor(Math.random()*10); 
			
		} 
		return Num.toString();
	}
	do {
		cid=newId();
	}
	while (cid in aliveClient);
	aliveClient[cid]=socket;
	aliveList[cid]={};
	aliveCount +=1;
	return cid;
}
function removeClient(cid){
	delete aliveClient[cid];
	delete aliveList[cid];
	aliveCount -=1;
}
function check(cid,cbk,res){
	global 
	var code=0;
	var msg=""
	if (cid in aliveClient) {

		var json={code:200,message:"执行成功"};
		cbk(json);
		
	}else {
		res.json({code:404,message:"找不到客户端编号"});
	}
	
}

function getsongbyid(id,cbk_in){
	down("http://music.163.com/api/song/detail/?id="+id+"&ids=%5B+"+id+"%5D&csrf_token=",function(d){
		var rtn=JSON.parse(d);
		if (rtn.code==200 && rtn.songs.length>0){
		var rsong=rtn.songs[0];

		var song={title: rsong.name,
					    artist: rsong.artists[0].name,
					    album: rsong.album.name,
					    cover: rsong.album.picUrl,
					    mp3: rsong.mp3Url,
					    ogg: '',
					    code:200,
					    message:"已添加歌曲："+rsong.name+" 表演者："+rsong.artists[0].name
			}
		console.log("add a song");
		cbk_in(song);
		}else{
			cbk_in({code:400, message:"歌曲添加失败，请检查id是否正确。"})
		}
	});
}



app.engine('handlebars',handlebars.engine);
app.set('view engine','handlebars');

app.set("port",process.env.PORT || 1339);


app.get('/header',function(req,res){
	res.type('text/plain');
	var s='';
	for (var i in req.headers ) {
		s += i + ':'+req.headers[i]+'\n';
	};
	res.send(s);
});


app.get("/",function(req,res){
	res.render("home");
})
app.get("/client",function(req,res){
	res.render('play');
});
app.get("/ctrl",function(req,res){
	res.render('ctrl');
})
app.get("/clientdo",function(req,res){
	var cid=req.query['cid'];
	var action=req.query['do'];
	check(cid,function(json){
		event=""
		switch (action){
			case "pp":
			event="Play/PauseSignal";
			break;

			case "nxt" :
			event="NextSignal";
			break;

			case "prv" :
			event="PrevSignal";
			break;

			case "vu" :
			event="VolupSignal";
			break;

			case "dll" :
			event="DelastSignal";
			break;

			case "vd" :
			event="VoldownSignal";
			break;

			default :
			json.code=400;
			json.message="找不到命令";
			break;
		}
		if (json.code==200){
			aliveClient[cid].emit(event);
		}
		res.json(json);
	},res);
});

app.get("/vaildclient",function(req,res){
	check(req.query['cid'],function(json){
		res.json(json);
	},res);

});

app.get("/list",function(req,res){
	var chk=check(req.query['cid'],function(json){
		res.json(aliveList[req.query['cid']]);
	},res);

});

app.get("/add",function(req,res){
  var cid=req.query["cid"];
  var sid=req.query['sid'];
	check(cid,function(json){
	getsongbyid(sid,function(song){
  		if (song.code == 200){
	  		aliveClient[cid].emit("AddSong",song);
		}
  		res.json(song);
  	});
  },res);
	
});

io.on('connection', function(socket){
	socket.cid=addClient(socket);
	socket.emit("NewClient",{id:socket.cid});
	socket.on('SyncPlayermeta',function(meta){
		aliveList[meta.cid]=meta;
	});
	socket.on('disconnect', function(soc){
		removeClient(socket.cid);
});
	console.log("Client Connected: "+socket.cid);

});


app.use(express.static(__dirname + '/public' ));

app.use(function(req,res){
	res.status(404);
	res.render('Error',{rip:((req.headers['x-real-ip'] != undefined ) ? req.headers['x-real-ip'] : req.ip),
						code:"404",
						message : "404-Not Found 喂！你在看人家哪里啊！>_< "});
});

app.use(function(err,req,res,next){
	console.log(err.stack);
	res.status(500);
	res.render('Error',{rip:((req.headers['x-real-ip'] != undefined ) ? req.headers['x-real-ip'] : req.ip),
						code:"500",
						message : "500-Server Internal Error 都是可恶的鹳狸猿的锅。人家坏掉了呢_(:з」∠)_ "});
});


http.listen(app.get("port"),function(){
	console.log("Hey There, Now I've set up~ "+app.get('port'));
});


